<template>
  <div class="payment-page">
    <div class="container">
      <!-- 页面头部 -->
      <div class="page-header">
        <el-button @click="handleBack" :icon="ArrowLeft" circle />
        <h1>订单支付</h1>
        <div class="placeholder"></div>
      </div>

      <!-- 支付倒计时 -->
      <el-card class="countdown-card" v-if="countdown > 0">
        <div class="countdown-content">
          <el-icon color="#e6a23c"><Clock /></el-icon>
          <span>请在 {{ formatCountdown(countdown) }} 内完成支付，超时订单将自动取消</span>
        </div>
      </el-card>

      <!-- 订单信息 -->
      <el-card class="order-info-card">
        <h3>订单信息</h3>
        <div class="order-content">
          <div class="service-info">
            <el-image
              :src="orderInfo.service?.image || '/default-service.jpg'"
              fit="cover"
              class="service-image"
            />
            <div class="service-details">
              <h4>{{ orderInfo.service?.name }}</h4>
              <p>{{ orderInfo.service?.description }}</p>
              <div class="service-meta">
                <span class="merchant-name">{{ orderInfo.merchant?.name }}</span>
              </div>
            </div>
          </div>
          
          <div class="order-details">
            <div class="detail-row">
              <span class="label">订单号</span>
              <span class="value">{{ orderInfo.orderNumber }}</span>
            </div>
            <div class="detail-row">
              <span class="label">服务时间</span>
              <span class="value">{{ formatDate(orderInfo.appointmentTime) }}</span>
            </div>
            <div class="detail-row">
              <span class="label">服务地址</span>
              <span class="value">{{ orderInfo.address?.fullAddress }}</span>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 费用明细 -->
      <el-card class="cost-details-card">
        <h3>费用明细</h3>
        <div class="cost-list">
          <div class="cost-item">
            <span class="cost-label">服务费用</span>
            <span class="cost-value">¥{{ formatAmount(orderInfo.serviceAmount) }}</span>
          </div>
          <div class="cost-item" v-if="orderInfo.couponDiscount > 0">
            <span class="cost-label">优惠券优惠</span>
            <span class="cost-value discount">-¥{{ formatAmount(orderInfo.couponDiscount) }}</span>
          </div>
          <div class="cost-item" v-if="orderInfo.platformDiscount > 0">
            <span class="cost-label">平台优惠</span>
            <span class="cost-value discount">-¥{{ formatAmount(orderInfo.platformDiscount) }}</span>
          </div>
          <el-divider />
          <div class="cost-item total">
            <span class="cost-label">实付金额</span>
            <span class="cost-value">¥{{ formatAmount(orderInfo.totalAmount) }}</span>
          </div>
        </div>
      </el-card>

      <!-- 支付方式 -->
      <el-card class="payment-methods-card">
        <h3>选择支付方式</h3>
        <div class="payment-methods">
          <div
            v-for="method in paymentMethods"
            :key="method.type"
            class="payment-method"
            :class="{ 'selected': selectedPaymentMethod === method.type }"
            @click="selectPaymentMethod(method.type)"
          >
            <div class="method-icon">
              <el-image :src="method.icon" fit="contain" />
            </div>
            <div class="method-info">
              <h4>{{ method.name }}</h4>
              <p>{{ method.description }}</p>
            </div>
            <div class="method-radio">
              <el-radio :model-value="selectedPaymentMethod" :label="method.type" />
            </div>
          </div>
        </div>
      </el-card>

      <!-- 优惠券选择 -->
      <el-card class="coupon-card">
        <div class="coupon-header" @click="showCouponDialog = true">
          <div class="coupon-info">
            <el-icon><Ticket /></el-icon>
            <span v-if="selectedCoupon">
              已选择优惠券：{{ selectedCoupon.title }} (-¥{{ selectedCoupon.amount }})
            </span>
            <span v-else>选择优惠券</span>
          </div>
          <el-icon><ArrowRight /></el-icon>
        </div>
      </el-card>

      <!-- 支付按钮 -->
      <div class="payment-action">
        <el-button
          type="primary"
          size="large"
          @click="handlePayment"
          :loading="paymentLoading"
          :disabled="!selectedPaymentMethod"
          class="payment-btn"
        >
          立即支付 ¥{{ formatAmount(orderInfo.totalAmount) }}
        </el-button>
      </div>
    </div>

    <!-- 优惠券选择对话框 -->
    <el-dialog
      v-model="showCouponDialog"
      title="选择优惠券"
      width="600px"
    >
      <div class="coupon-list">
        <div
          v-for="coupon in availableCoupons"
          :key="coupon.id"
          class="coupon-item"
          :class="{ 'selected': selectedCoupon?.id === coupon.id }"
          @click="selectCoupon(coupon)"
        >
          <div class="coupon-left">
            <div class="coupon-amount">¥{{ coupon.amount }}</div>
            <div class="coupon-condition">
              {{ coupon.minAmount > 0 ? `满${coupon.minAmount}可用` : '无门槛' }}
            </div>
          </div>
          <div class="coupon-right">
            <h4>{{ coupon.title }}</h4>
            <p>{{ coupon.description }}</p>
            <div class="coupon-time">
              有效期至 {{ formatDate(coupon.validUntil) }}
            </div>
          </div>
        </div>
        
        <div class="no-coupon-option" @click="selectCoupon(null)">
          <el-radio :model-value="!selectedCoupon" :label="true">
            不使用优惠券
          </el-radio>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showCouponDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmCouponSelection">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 支付成功对话框 -->
    <el-dialog
      v-model="showSuccessDialog"
      title="支付成功"
      width="400px"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <div class="success-content">
        <el-icon size="60" color="#67c23a"><SuccessFilled /></el-icon>
        <h3>支付成功！</h3>
        <p>您的订单已支付完成，商家将尽快为您安排服务</p>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="goToOrderDetail">查看订单</el-button>
          <el-button type="primary" @click="goToHome">返回首页</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft,
  Clock,
  Ticket,
  ArrowRight,
  SuccessFilled
} from '@element-plus/icons-vue'
import { orderApi, couponApi, paymentApi } from '@/services/api'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()

// 数据定义
const orderInfo = ref({})
const loading = ref(true)
const paymentLoading = ref(false)
const countdown = ref(1800) // 30分钟倒计时
const selectedPaymentMethod = ref('')
const selectedCoupon = ref(null)
const showCouponDialog = ref(false)
const showSuccessDialog = ref(false)
const availableCoupons = ref([])

let countdownTimer = null

const paymentMethods = ref([
  {
    type: 'alipay',
    name: '支付宝',
    description: '推荐使用支付宝快捷支付',
    icon: '/payment-icons/alipay.svg'
  },
  {
    type: 'wechat',
    name: '微信支付',
    description: '使用微信余额、银行卡支付',
    icon: '/payment-icons/wechat.svg'
  },
  {
    type: 'balance',
    name: '余额支付',
    description: '使用账户余额支付',
    icon: '/payment-icons/balance.svg'
  }
])

// 生命周期
onMounted(() => {
  fetchOrderInfo()
  fetchAvailableCoupons()
  startCountdown()
})

onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})

// 方法定义
const fetchOrderInfo = async () => {
  try {
    loading.value = true
    const response = await orderApi.getOrderDetail(route.params.orderId)
    orderInfo.value = response.data
    
    if (orderInfo.value.status !== 'pending_payment') {
      ElMessage.warning('订单状态已变更')
      router.back()
    }
  } catch (error) {
    console.error('获取订单信息失败:', error)
    ElMessage.error('获取订单信息失败')
  } finally {
    loading.value = false
  }
}

const fetchAvailableCoupons = async () => {
  try {
    const response = await couponApi.getAvailableCoupons({
      merchantId: orderInfo.value.merchant?.id,
      serviceId: orderInfo.value.service?.id,
      amount: orderInfo.value.serviceAmount
    })
    availableCoupons.value = response.data
  } catch (error) {
    console.error('获取可用优惠券失败:', error)
  }
}

const startCountdown = () => {
  countdownTimer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(countdownTimer)
      ElMessage.warning('支付超时，订单已取消')
      router.push('/orders')
    }
  }, 1000)
}

const selectPaymentMethod = (method) => {
  selectedPaymentMethod.value = method
}

const selectCoupon = (coupon) => {
  selectedCoupon.value = coupon
}

const confirmCouponSelection = () => {
  showCouponDialog.value = false
  // 重新计算订单金额
  calculateTotalAmount()
}

const calculateTotalAmount = () => {
  let totalAmount = orderInfo.value.serviceAmount
  if (selectedCoupon.value) {
    totalAmount -= selectedCoupon.value.amount
  }
  orderInfo.value.totalAmount = Math.max(totalAmount, 0)
}

const handlePayment = async () => {
  if (!selectedPaymentMethod.value) {
    ElMessage.warning('请选择支付方式')
    return
  }

  try {
    paymentLoading.value = true
    
    const paymentData = {
      orderId: route.params.orderId,
      paymentMethod: selectedPaymentMethod.value,
      couponId: selectedCoupon.value?.id,
      amount: orderInfo.value.totalAmount
    }

    const response = await paymentApi.createPayment(paymentData)
    
    // 根据支付方式处理支付流程
    await processPayment(response.data)
    
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付失败，请重试')
  } finally {
    paymentLoading.value = false
  }
}

const processPayment = async (paymentInfo) => {
  switch (selectedPaymentMethod.value) {
    case 'alipay':
    case 'wechat':
      // 跳转到第三方支付页面
      window.open(paymentInfo.paymentUrl, '_blank')
      
      // 轮询支付结果
      checkPaymentStatus(paymentInfo.paymentId)
      break
      
    case 'balance':
      // 余额支付直接完成
      showSuccessDialog.value = true
      clearInterval(countdownTimer)
      break
  }
}

const checkPaymentStatus = async (paymentId) => {
  const checkTimer = setInterval(async () => {
    try {
      const response = await paymentApi.getPaymentStatus(paymentId)
      
      if (response.data.status === 'success') {
        clearInterval(checkTimer)
        clearInterval(countdownTimer)
        showSuccessDialog.value = true
      } else if (response.data.status === 'failed') {
        clearInterval(checkTimer)
        ElMessage.error('支付失败')
      }
    } catch (error) {
      console.error('查询支付状态失败:', error)
    }
  }, 2000) // 每2秒查询一次

  // 5分钟后停止查询
  setTimeout(() => {
    clearInterval(checkTimer)
  }, 300000)
}

const handleBack = () => {
  ElMessageBox.confirm(
    '确定要退出支付吗？退出后需要重新进入支付页面',
    '提示',
    {
      confirmButtonText: '确定退出',
      cancelButtonText: '继续支付',
      type: 'warning'
    }
  ).then(() => {
    router.back()
  }).catch(() => {
    // 用户取消
  })
}

const goToOrderDetail = () => {
  router.push(`/orders/${route.params.orderId}`)
}

const goToHome = () => {
  router.push('/home')
}

const formatCountdown = (seconds) => {
  const minutes = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

const formatAmount = (amount) => {
  return parseFloat(amount || 0).toFixed(2)
}

const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}
</script>

<style lang="scss" scoped>
.payment-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px 0;
}

.container {
  max-width: 600px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;

  h1 {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #333;
  }

  .placeholder {
    width: 32px;
  }
}

.el-card {
  margin-bottom: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.countdown-card {
  .countdown-content {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #e6a23c;
    font-weight: 500;

    .el-icon {
      font-size: 18px;
    }
  }
}

.order-info-card {
  h3 {
    margin: 0 0 16px 0;
    font-size: 16px;
    font-weight: 600;
  }

  .order-content {
    .service-info {
      display: flex;
      gap: 12px;
      margin-bottom: 16px;

      .service-image {
        width: 80px;
        height: 80px;
        border-radius: 8px;
        flex-shrink: 0;
      }

      .service-details {
        flex: 1;

        h4 {
          margin: 0 0 4px 0;
          font-size: 14px;
          font-weight: 500;
        }

        p {
          margin: 0 0 8px 0;
          color: #666;
          font-size: 12px;
        }

        .merchant-name {
          color: #409eff;
          font-size: 12px;
        }
      }
    }

    .order-details {
      .detail-row {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;

        .label {
          color: #666;
          font-size: 14px;
        }

        .value {
          color: #333;
          font-size: 14px;
        }
      }
    }
  }
}

.cost-details-card {
  h3 {
    margin: 0 0 16px 0;
    font-size: 16px;
    font-weight: 600;
  }

  .cost-list {
    .cost-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;

      &.total {
        font-weight: 600;
        font-size: 16px;

        .cost-value {
          color: #e6a23c;
        }
      }

      .cost-label {
        color: #666;
      }

      .cost-value {
        color: #333;

        &.discount {
          color: #67c23a;
        }
      }
    }
  }
}

.payment-methods-card {
  h3 {
    margin: 0 0 16px 0;
    font-size: 16px;
    font-weight: 600;
  }

  .payment-methods {
    .payment-method {
      display: flex;
      align-items: center;
      padding: 12px;
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      margin-bottom: 8px;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        border-color: #409eff;
      }

      &.selected {
        border-color: #409eff;
        background-color: #f0f9ff;
      }

      .method-icon {
        width: 40px;
        height: 40px;
        margin-right: 12px;

        .el-image {
          width: 100%;
          height: 100%;
        }
      }

      .method-info {
        flex: 1;

        h4 {
          margin: 0 0 4px 0;
          font-size: 14px;
          font-weight: 500;
        }

        p {
          margin: 0;
          color: #666;
          font-size: 12px;
        }
      }

      .method-radio {
        margin-left: 12px;
      }
    }
  }
}

.coupon-card {
  :deep(.el-card__body) {
    padding: 0;
  }

  .coupon-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    cursor: pointer;

    .coupon-info {
      display: flex;
      align-items: center;
      gap: 8px;
      color: #e6a23c;
    }
  }
}

.payment-action {
  position: sticky;
  bottom: 20px;
  padding: 16px 0;
  background: #f5f7fa;

  .payment-btn {
    width: 100%;
    height: 48px;
    font-size: 16px;
    font-weight: 600;
  }
}

.coupon-list {
  max-height: 400px;
  overflow-y: auto;

  .coupon-item {
    display: flex;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    margin-bottom: 8px;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      border-color: #409eff;
    }

    &.selected {
      border-color: #409eff;
      background-color: #f0f9ff;
    }

    .coupon-left {
      width: 100px;
      background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
      color: white;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      padding: 16px;

      .coupon-amount {
        font-size: 20px;
        font-weight: 600;
        margin-bottom: 4px;
      }

      .coupon-condition {
        font-size: 12px;
        opacity: 0.9;
      }
    }

    .coupon-right {
      flex: 1;
      padding: 12px;

      h4 {
        margin: 0 0 4px 0;
        font-size: 14px;
        font-weight: 500;
      }

      p {
        margin: 0 0 8px 0;
        color: #666;
        font-size: 12px;
      }

      .coupon-time {
        color: #999;
        font-size: 12px;
      }
    }
  }

  .no-coupon-option {
    padding: 16px;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    cursor: pointer;
    text-align: center;

    &:hover {
      border-color: #409eff;
    }
  }
}

.success-content {
  text-align: center;
  padding: 20px 0;

  h3 {
    margin: 16px 0 8px 0;
    color: #333;
  }

  p {
    margin: 0;
    color: #666;
    line-height: 1.5;
  }
}

@media (max-width: 768px) {
  .container {
    padding: 0 10px;
  }

  .service-info {
    flex-direction: column;

    .service-image {
      align-self: center;
    }
  }

  .payment-action {
    bottom: 10px;
    left: 10px;
    right: 10px;
    padding: 0;
  }
}
</style> 